package com.briup.server.service.impl;

import com.briup.common.constant.SystemConstant;
import com.briup.common.exception.ServiceException;
import com.briup.common.response.ResultCode;
import com.briup.server.config.EmailSupporter;
import com.briup.server.domain.dto.KaptchaVerifyRequest;
import com.briup.server.service.KaptchaService;
import com.google.code.kaptcha.Producer;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;


@Service
@RequiredArgsConstructor
public class KaptchaServiceImpl implements KaptchaService {

    private final Producer kaptchaProducer;
    private final EmailSupporter emailSupporter;
    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public BufferedImage getCaptcha(String formId) {
        // 1. 生成验证码字符串
        String kaptchaText = kaptchaProducer.createText();
        // 将验证码存储到 Redis 中
        save(formId, kaptchaText);
        // 3. 生成验证码图片
        return kaptchaProducer.createImage(kaptchaText);
    }

    @Override
    public void sendCode(String email) {
        // 生成验证码，借助于 captchaProducer
        String captchaText = kaptchaProducer.createText();

        // 借助于 emailSupporter 发送验证码邮件
        emailSupporter.sendVerifyCode(email, captchaText);

        // 将验证码存储到 Redis 中
        save(email, captchaText);
    }

    @Override
    public boolean verifyCaptcha(KaptchaVerifyRequest request) {
        // 1. 根据formId查询验证码，从 Redis 中获取
        String captchaText = (String) redisTemplate.opsForValue()
                .get("kaptcha-" + request.getFormId());

        // 2. 检查验证码是否存在
        if (captchaText == null) {
            throw new ServiceException(ResultCode.CAPTCHA_EXPIRED);
        }

        // 3. 验证验证码是否匹配（忽略大小写）
        if (!captchaText.equalsIgnoreCase(request.getKaptcha())) {
            throw new ServiceException(ResultCode.CAPTCHA_ERROR);
        }

        return true;
    }

    /**
     * 将验证码存储到 Redis 中
     *
     * @param formId      表单ID
     * @param captchaText 验证码文本
     */
    private void save(String formId, String captchaText) {
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        operations.set("kaptcha-" + formId, captchaText,
                SystemConstant.CAPTCHA_EXPIRE_MINUTES, TimeUnit.MINUTES);
    }
}




